﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.User;
using B.S.BasicData.Domian.Entities.Account;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.BasicData.Api.Read.Application.Handler.User
{
    public class UpdateHandler : IRequestHandler<UpdateCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<AccountModel> accountRepo;
        private readonly IMapper mapper;

        public UpdateHandler(IBaseRepository<AccountModel> accountRepo, IMapper mapper)
        {
            this.accountRepo = accountRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(UpdateCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();
            var account = accountRepo.GetAll().Where(x => x.Name == request.Name && x.Id != request.Id).FirstOrDefault();
            if (account != null)
            {
                res.Message = "用户名已存在";
                res.Code = ApiEnum.Error;
                return Task.FromResult(res);
            }
            var entity = mapper.Map(request, account);
            var r = accountRepo.Update(entity).Result;
            if (r > 0)
            {
                res.Message = "修改成功";
                res.Code = ApiEnum.Ok;
                res.Data = r;
            }
            else
            {
                res.Message = "修改失败";
                res.Code = ApiEnum.Error;
                res.Data = r;
            }
            return Task.FromResult(res);

        }
    }
}
